<template>
  <div id="market_gameticket_times">
    <div class="search-box">
      <Row type="flex">
        <Row type="flex" justify="start" class="search-item-left">
          <Col class="search-item"><span class="search-label">活动名称:</span><Input placeholder="请输入" :maxlength="20" @on-keyup='filterSpace' @on-blur="filterSpace" v-model='activityName'></Input></Col>
          <Col class="search-item">
            <span class="search-label">场景类型:</span>
            <Select v-model="searchObj.activityType" @on-change="doSearch"
              style="width:180px">
              <Option :value="-1">全部</Option>
              <Option v-for="item in typeList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </Col>
          <Col class="search-item">
            <span class="search-label">活动状态:</span>
            <Select v-model="searchObj.activityStatus" @on-change="doSearch"
              style="width:180px">
              <Option :value="-1">全部</Option>
              <Option v-for="item in statusList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  type='primary'
                  @click="doSearch"
                  >查询</Button>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                @click="reset">重置</Button>
          </Col>
        </Row>
        <Row type="flex" justify="end" class="search-item-right">
          <Col class="search-item">
          <Dropdown trigger="click" @on-visible-change="dropVisible=!dropVisible" @on-click="skipAdd">
          <Button class="search-btn" type="primary"  v-if="hasPermission('moms:market:activitycreate')">创建
            <Icon :type="dropVisible ? 'ios-arrow-up' : 'ios-arrow-down'"></Icon>
          </Button>
          <DropdownMenu slot="list">
            <DropdownItem  :name="item.value" v-for="(item, index) in typeList" :key="index">{{item.label}}</DropdownItem>
          </DropdownMenu>
        </Dropdown>
          </Col>
        </Row>
      </Row>
    </div>
    <Table stripe class="table-list" :columns="columns" :data="data" :loading="loading" :height="this.tableHeight">
      <template slot-scope="{ row }" slot="activityType">
        {{ getEnumsName(row.activityType, typeList) }}
      </template>
      <template slot-scope="{ row }" slot="activityStatus">
        {{ getEnumsName(row.activityStatus, statusList) }}
      </template>
      <template slot-scope="{ row }" slot="action">
        <i class="iconsys icondetail" title="查看" @click='skipDetail(row)' v-if="hasPermission('moms:market:activitydetail')"></i>
        <Poptip width="190" trigger="hover">
          <i class="iconsys iconshengchengerweima" title="二维码" @mouseover='handleEwm(row)' v-if="row.activityStatus === 1 && (row.activityType === 1 || row.activityType === 2 || row.activityType === 3 || row.activityType === 11)"></i>
          <div style="height:200px; text-align:center;" slot="content" >
            <Spin fix v-if="!row.ewmPath"></Spin>
            <div v-if="row.ewmPath">
              <img :src="row.ewmPath" width="150">
              <p><a :href="row.ewmPath" :download="row.activityType === 11 ? '分享二维码.png' : '小游戏二维码.png'">下载二维码</a></p>
            </div>
          </div>
        </Poptip>
        <i class="iconsys iconedit" title="编辑" @click='skipEdit(row)' v-if="hasPermission('moms:market:activityupdate') && row.activityStatus === 0"></i>
        <Poptip confirm title="你确定要删除吗？" transfer @on-ok="sureDel(row)"
        v-if="hasPermission('moms:market:activitydelete')  && row.activityStatus === 0"
        style="text-align:left">
          <i class="iconsys icondel" title="删除" ></i>
        </Poptip>
        <Poptip confirm title="你确定要立即结束吗？" transfer @on-ok="sureClose(row)"
        v-if="hasPermission('moms:market:activityclose')  && row.activityStatus === 1"
        style="text-align:left">
          <i class="iconsys iconxiajia" title="立即结束" ></i>
        </Poptip>
      </template>
    </Table>
    <Row type='flex' justify="end" style='padding: 20px'>
      <Col>
        <Page :total="total"
              :page-size='pageSize'
              :current='pageIndex'
              show-total
              show-sizer
              @on-change='changePageIndex'
              @on-page-size-change='changePageSize' />
      </Col>
    </Row>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getActiveLists, closeActive, delActive, qrCodeActive, qrCodeShare } from '@/api/market/active.js'
// import { getBrandList } from '@/api/merchant.js'
import enumsMixin from '../enums.js'
// let that
export default {
  name: 'market_active_list',
  mixins: [enumsMixin],
  data () {
    return {
      dropVisible: false,
      activityName: '',
      searchObj: {
        activityName: '',
        activityType: -1,
        activityStatus: -1
      },
      total: 0,
      pageSize: 10,
      pageIndex: 1,
      loading: false,
      tableHeight: 0,
      columns: [
        {
          title: '活动编号',
          key: 'activityCode'
        },
        {
          title: '场景类型',
          slot: 'activityType'
        },
        {
          title: '活动名称',
          key: 'activityName'
        },
        {
          title: '活动开始时间',
          key: 'activityStart'
        },
        {
          title: '活动结束时间',
          key: 'activityEnd'
        },
        {
          title: '活动状态',
          slot: 'activityStatus'
        },
        {
          title: '创建时间',
          key: 'createTime'
        }
      ],
      data: []
      // brandList: []
    }
  },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId,
      userId: state => state.user.userId,
      userName: state => state.user.userName
    })
  },
  // beforeCreate: function () {
  //   that = this
  // },
  // filters: {
  //   getBrandsName (value) {
  //     if (value) {
  //       let arr = value.split(',')
  //       return arr.map((value) => {
  //         const result = that.brandList.filter(item => item['brandId'] === value)
  //         return result[0] ? result[0]['brandName'] : ''
  //       }).join(',')
  //     }
  //     return ''
  //   }
  // },
  watch: {
    '$route' (newRoute) {
      if (newRoute.name === 'market_active_list') {
        this.getData()
      }
    }
  },
  mounted () {
    this.getData()
    if (this.hasPermission(['moms:market:activityupdate', 'moms:market:activitydelete', 'moms:market:activitydetail', 'moms:market:activityclose'])) {
      this.columns.push({
        title: '操作',
        slot: 'action',
        width: 180
      })
    }
    // getBrandList({
    //   merchantId: this.merchantId
    // }).then(res => {
    //   const result = res.data || {}
    //   if (result.status === 200) {
    //     this.brandList = result.data
    //   } else {
    //     this.$Message.error(`${result.error}`)
    //   }
    // }).catch(err => {
    //   this.$Message.error(`${err}`)
    // })
  },
  methods: {
    handleEwm (row) {
      if (!row.ewmPath) {
        if (row.activityType === 1 || row.activityType === 2 || row.activityType === 3) {
          qrCodeActive({
            merchantId: this.merchantId,
            activityId: row.activityId
          }).then(res => {
            const result = res.data || {}
            if (result.status === 200) {
              this.$set(this.data[row._index], 'ewmPath', 'data:image/png;base64,' + result.data)
            } else {
              this.$Message.error(`${result.error}`)
            }
          }).catch(err => {
            this.$Message.error(`${err}`)
          })
        } else if (row.activityType === 11) {
          qrCodeShare({
            merchantId: this.merchantId,
            activityId: row.activityId,
            shareMemberId: this.userId,
            activityName: row.activityName,
            orderCode: row.activityCode
          }).then(res => {
            const result = res.data || {}
            if (result.status === 200) {
              this.$set(this.data[row._index], 'ewmPath', 'data:image/png;base64,' + result.data)
            } else {
              this.$Message.error(`${result.error}`)
            }
          }).catch(err => {
            this.$Message.error(`${err}`)
          })
        }
      }
    },
    filterSpace () {
      this.activityName = this.activityName.replace(/\s+/g, '')
    },
    skipAdd (id) {
      this.$router.push({ name: 'market_active_create', params: { type: id } })
    },
    skipDetail (row) {
      this.$router.push({
        name: 'market_active_detail',
        params: {
          id: row.activityId,
          type: row.activityType
        }
      })
    },
    skipEdit (row) {
      this.$router.push({
        name: 'market_active_edit',
        params: {
          id: row.activityId,
          type: row.activityType
        }
      })
    },
    getData () {
      this.loading = true
      this.tableHeight = 0
      var params = {
        merchantId: this.merchantId,
        activityName: this.searchObj.activityName,
        offset: (this.pageIndex - 1) * this.pageSize,
        limit: this.pageSize
      }
      if (this.searchObj.activityType !== -1) {
        params.activityType = this.searchObj.activityType
      }
      if (this.searchObj.activityStatus !== -1) {
        params.activityStatus = this.searchObj.activityStatus
      }
      getActiveLists(params).then(res => {
        this.loading = false
        const result = res.data || {}
        if (result.status === 200) {
          this.data = result.data || [].map(item => {
            item.ewmPath = ''
            return item
          })
          this.total = result.totalCount || 0
          if (this.data.length > 10) {
            this.tableHeight = 520
          }
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
        this.loading = false
      })
    },
    sureDel (row) {
      delActive({
        activityId: row.activityId
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.$Message.success('删除成功！')
          setTimeout(() => {
            this.getData()
          }, 300)
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    sureClose (row) {
      closeActive({
        merchantId: this.merchantId,
        activityId: row.activityId,
        activityStatus: 2,
        operatorName: this.userName,
        operatorId: this.userId
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.$Message.success('结束活动成功！')
          this.getData()
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    search () {
      this.pageIndex = 1
      this.getData()
    },
    doSearch () {
      this.searchObj.activityName = this.activityName
      this.search()
    },
    reset () {
      this.activityName = ''
      this.searchObj = {
        activityName: '',
        activityType: -1,
        activityStatus: -1
      }
      this.search()
    },
    changePageIndex (page) {
      this.pageIndex = page
      this.getData()
    },
    changePageSize (size) {
      this.pageSize = size
      this.search()
    }
  }
}
</script>
